package com.liruo.treasureattic.gateway.filter;

import com.liruo.treasureattic.gateway.model.GlobalFilterOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:liruo
 * @Date:2022-10-08-21:54:33
 * @Desc
 */
@Order(GlobalFilterOrder.LOGGING_REQUEST_HANDLER_INFO)
@Component
@Slf4j
public class ApiLogGlobalFilter implements GlobalFilter {
    private static final String START_TIME = "apiStartTime";

    //一般是从nginx转发来的，因此需要在nginx配置，这里就给请求加一个X-Real-IP的header=请求的源ip
    private static final String X_REAL_IP = "X-Real-IP";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        LinkedHashSet<URI> uris = (LinkedHashSet) exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        //不要uri是lb的，获取到原来的请求
        List<URI> uriList = uris.stream()
                .filter(uri -> !uri.getScheme().equals("lb"))
                .collect(Collectors.toList());
        //        if (log.isDebugEnabled()) {
        ServerHttpRequest request = exchange.getRequest();
        //SchemeSpecificPart=RawSchemeSpecificPart
            log.info("Method={}  URI={}",
                    request.getMethodValue(),
                    uriList.size() == 1 ? uriList.get(0) : uriList
            );
        //localhost:9000
        //exchange.getRequest().getURI().getAuthority()
//        }
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long executeTime = (System.currentTimeMillis() - startTime);
                List<String> ips = request.getHeaders().get(X_REAL_IP);
                String ip = ips != null ? ips.get(0) : null;
                String api = request.getURI().getRawPath();

                int code = 500;
                if (exchange.getResponse().getStatusCode() != null) {
                    code = exchange.getResponse().getStatusCode().value();
                }
                // 当前仅记录日志，后续可以添加日志队列，来过滤请求慢的接口
//                if (log.isDebugEnabled()) {
                    log.info("real-IP={} lbPath={}，response-code={}，usedTime={}ms now-originalRequest={}",
                            ip, api, code, executeTime,uriList.size() == 1 ? uriList.get(0) : uriList
                    );
//                }
            }
        }));
    }
}
